﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Nirvana
{
    [ExecuteInEditMode]
    [AddComponentMenu("Nirvana/Render/Batch Renderer")]
    public class BatchRenderer : MonoBehaviour
    {

        [Tooltip("The template material.")]
        [SerializeField]
        private Material templateMaterial;

        [Tooltip("The main texture")]
        [SerializeField]
        private Texture mainTexture;

        public Material TemplateMaterial
        {
            get
            {
                return this.templateMaterial;
            }
        }

        public Texture MainTexture
        {
            get
            {
                return this.mainTexture;
            }
        }

        void Awake()
        {
            Init();
        }

#if UNITY_EDITOR
        void OnValidate()
        {
            Init();
        }
#endif

        public void FindTexture()
        {
            this.mainTexture = GetMainTexture();
        }

        private Texture GetMainTexture()
        {
            NirvanaRenderer nirvanaRenderer = GetComponent<NirvanaRenderer>();
            if(nirvanaRenderer != null && nirvanaRenderer.Materials.Length > 0)
            {
                var mat = nirvanaRenderer.Materials[0];
                if (mat != null && mat.mainTexture != null) return mat.mainTexture;
            }

            Renderer renderer = GetComponent<Renderer>();
            if (renderer != null )
            {
                var mat = renderer.sharedMaterial;
                if (mat != null && mat.mainTexture != null) return mat.mainTexture;
            }
            return null;
        }


        private void Init()
        {
            if (this.mainTexture == null || this.templateMaterial == null) return;
            NirvanaRenderer nirvanaRenderer = GetComponent<NirvanaRenderer>();
            if (nirvanaRenderer != null )
            {
                nirvanaRenderer.Materials = new Material[]
                {
                    new Material(this.templateMaterial)
                    {
                        name = string.Format("{0}:{1}", this.templateMaterial.name, this.mainTexture),
                        mainTexture = this.mainTexture,
                        hideFlags =  HideFlags.HideAndDontSave
                    }
                };
                return;
            }

            Renderer renderer = GetComponent<Renderer>();
            if (renderer != null)
            {
                renderer.sharedMaterial = new Material(this.templateMaterial)
                {
                    name = string.Format("{0}:{1}", this.templateMaterial.name, this.mainTexture),
                    mainTexture = this.mainTexture,
                    hideFlags = HideFlags.HideAndDontSave

                };

                return;
            }

        }

    }
}

